package edu.utsa.cs.vignette.pdf;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;

public class PDFMain {

	public static void main(String args[]) {
		if (args.length < 2
				|| (!args[0].toLowerCase().contains("png") && args.length < 3)) {
			System.err.println("Check usage");
			return;
		}

		if (args[0].toLowerCase().contains("cat")
				|| args[0].toLowerCase().contains("merge")) {
			String pdfList[] = new String[args.length - 1];
			for (int i = 1; i < args.length; i++) {
				pdfList[i - 1] = args[i];
			}
			try {
				String resultPath = File.createTempFile("pdf", ".pdf")
						.getAbsolutePath();
				PDF.MergePDFsAndWrite(pdfList, resultPath);
				System.out.println(resultPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (args[0].toLowerCase().contains("split")) {
			try {
				List<PDDocument> docs = PDF.splitEveryNPages(Integer
						.parseInt(args[2]), args[1]);
				String resultPrefix = File.createTempFile("pdf", "")
						.getAbsolutePath();
				int i = -1;
				for (PDDocument doc : docs) {
					String resultPath = resultPrefix + Integer.toString(++i)
							+ ".pdf";
					doc.save(resultPath);
					System.out.println(resultPath);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (args[0].toLowerCase().contains("extract")) {
			try {
				String resultPath = File.createTempFile("pdf", ".pdf")
						.getAbsolutePath();
				PDDocument doc = PDF.extractPage(Integer.parseInt(args[2]),
						args[1]);
				doc.save(resultPath);
				System.out.println(resultPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (args[0].toLowerCase().contains("png")) {
			// try {
			// String resultPath = File.createTempFile("pdf",
			// "").getAbsolutePath();
			// PDF.generatePNG(args[1], resultPath);
			// System.out.println(resultPath + "1.png");
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			try {
				String png = File.createTempFile("pdf", ".png")
						.getCanonicalPath();
				int width;
				try {
					width = Integer.parseInt(args[3]);
				} catch (Exception e) {
					width = 640;
				}
				ProcessBuilder pb = new ProcessBuilder("convert", args[1],
						"-delete", "1--1", "-resize", Integer.toString(width), png);
				System.err.println(pb.toString());
				System.err.println("Starting process...");
				Process p = pb.start();
				int retVal = 0;
				retVal = p.waitFor();
				if (retVal == 0) {
					System.out.println(png);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
